require.config({
    baseUrl : 'resources/backbone',
    shim: {
    },
    paths : {
        text : "libs/text",
        router : "routers/router",
        require_utils : "utils/require_utils",
        
        map_view : "views/map_view",
        boiler_tpl_view : "views/boiler_tpl_view",
        calculate_data_view : "views/calculate_data_view",
        menu_view : "views/menu_view",
        mail_content_view : "views/mail_content_view",
        canvas_plugin : "custom-plugin/canvas/canvas-object-01",
        
        dashboard : "custom-plugin/dashboard/dashboard",
    }
});


var getRoleUserAjax = function() {
	var jsonData = {
		action : "getRole"
	};
	return $.ajax({
		url : './rule',
		type : 'GET',
		data : jsonData,
		dataType : 'json',
		success : function(dataRoleUser) {
			// selt.jsonString= data;
		}
	});
	// return jsonString;
};
var addUserAjax = function() {
	event.preventDefault();
	var jsonData = {
		action : "addUser",
		user : JSON.stringify({
			username : $("#user-name").val(),
			password : $("#password").val(),
			firstName : $("#first-name").val(),
			lastName : $("#last-name").val(),
			gender : $("#gender").val(),
			birthday : $("#birthday").val(),
			email : $("#email").val(),
			mobile : $("#mobile").val(),
			status : $("#status").val(),
		})
	};
	$.ajax({
		url : './user',
		type : 'POST',
		data : jsonData,
		dataType : 'json',
		success : function(data) {

			if (data == true) {
				alert("create accout finish!");
			}
		},
		error : function(xhr, ajaxOptions, thrownError) {
			alert(xhr.status);
			alert(thrownError);
		}
	});

};
var updateUserAjax = function() {
	var multipleValues = $("#selected-group").val() || [];
	event.preventDefault();
	var jsonData = {
		action : "updateUser",
		roleUser : multipleValues.toString(),
		user : JSON.stringify({
			username : $("#user-name").val(),
			password : $("#password").val(),
			firstName : $("#first-name").val(),
			lastName : $("#last-name").val(),
			gender : $("#gender").val(),
			birthday : $("#birthday").val(),
			email : $("#email").val(),
			mobile : $("#mobile").val(),
			status : $("#status").val(),
		})
	};
	$.ajax({
		url : './user',
		type : 'POST',
		data : jsonData,
		dataType : 'json',
		success : function(data) {

			if (data == true) {
				alert("update accout finish!");
				var router = new Router();
				router.navigate('index/view', true);
			}
		},
		error : function(xhr, ajaxOptions, thrownError) {
			alert(xhr.status);
			alert(thrownError);
		}
	});

};
var getUserAjax = function(idUser) {

	var jsonData = {
		action : "editUser",
		editID : idUser
	};
	return $.ajax({
		url : './user',
		type : 'POST',
		data : jsonData,
		dataType : 'json',
		success : function(dataGetUser) {

			// var viewEditUser=new ViewAddUser();
			// viewEditUser.render(dataGetUser);
		}
	});

};
var deleteUserAjax = function(idUser) {
	var jsonData = {
		action : "deleteUser",
		deleteID : idUser
	};
	$.ajax({
		url : './user',
		type : 'POST',
		data : jsonData,
		dataType : 'json',
		success : function(data) {
			if (data == true) {
				alert("delete success :" + idUser);
				var viewAll = new ViewAllUser();
				viewAll.render();
			} else {
				alert("delete Fail :" + idUser);
			}
		}
	});

};
var ViewAddUser = Backbone.View.extend({
	el : '#container-body',
	templateAddUser : _.template($('#user-template').html()),
	initialize : function() {
		console.log("View initialize");
	},

	render : function(data1) {
		var that = this;
		console.log("View render");
		if (data1 != null) {
			// var jsonData = {action : "getRole"};
			// $.ajax({
			// url : 'role',
			// type : 'POST',
			// data : jsonData,
			// dataType : 'json',
			// success : function(data2) {
			// var variable={User:data1,Roles:data2};
			// that.$el.html(that.templateAddUser(variable));
			// }
			// });
			$.when(getRoleUserAjax(), getUserAjax(data1)).done(
					function(dataRoleUser, dataGetUser) {

						console.log(dataGetUser.username);
						var variable = {
							User : dataGetUser[0],
							Roles : dataRoleUser[0]
						};
						that.$el.html(that.templateAddUser(variable));
					});
		} else {
			that.$el.html(this.templateAddUser);
		}
		return that;
	},

	events : {
		"click #btn-create-new" : "createUser",
		"click #btn-view-all-user" : "showAllUser",
		"click #btn-cancle-edit-user" : "cancleEditUser",
		"click #btn-ok-edit-user" : "okEditUser",
	},
	okEditUser : function() {
		updateUserAjax();
	},
	cancleEditUser : function() {
		var router = new Router();
		router.navigate('index/view', true);
	},
	createUser : function() {
		addUserAjax();
	},
	showAllUser : function() {
		var router = new Router();
		router.navigate('index/view', {
			trigger : true
		});
	}
});

var ViewAllUser = Backbone.View.extend({
	el : '#container-body',
	templateManagerUser : _.template($('#user-manager-template').html()),

	initialize : function() {
		console.log("View initialize");
	},

	render : function() {
		var that = this;
		console.log("View render");
		var jsonData = {
			action : "getAllUser"
		};
		$.ajax({
			url : './user',
			type : 'GET',
			data : jsonData,
			dataType : 'json',
			success : function(data) {
				var variable = {
					dataArray : data
				};
				that.$el.html(that.templateManagerUser(variable));
			}
		});
		return false;
	},

	events : {
		"click button[name='btn-delete-user']" : "deleteUser",
		"click button[name='btn-edit-user']" : "editUser",
	},
	deleteUser : function(e) {
		var groupId = $(e.currentTarget).attr("groupId");
		deleteUserAjax(groupId);

	},
	editUser : function(e) {
		var groupId = $(e.currentTarget).attr("groupId");
		var router = new Router();
		router.navigate('index/edit/' + groupId, {
			trigger : true
		});
	}
});


var Router = Backbone.Router.extend({
	initialize : function() {
	    this.currentView = "";
		console.log("Router initialize");
	},
	index : function() {
		console.log("The index router");
	},
	routes : {
		"" : "index",
		"index" : "index",
		"index/view" : "viewAll",
		"index/edit/:id" : "editUser",
		"index/view/*path" : "showImage"
	},
	editUser : function(id) {
		var viewEditUser = new ViewAddUser();
		viewEditUser.render(id);
	},
	insertUser : function() {
		addUserAjax();
	},
	index : function() {

		var viewMap = new ViewMap();
		viewMap.render();
	},
	viewAll : function() {
		var viewAll = new ViewAllUser();
		viewAll.render();

	},

});


function initApp() {
    // START FOR AUTO LOAD MAP
    var view = router.currentView;
//    if(router.currentView.name == PAGE_MAP_VIEW){
//        autoLoad();
//    }
    // END FOR AUTO LOAD MAP
};

var autoInterval = null;
var i  = 0;
var autoLoad = function() {
    
    console.log('init autoLoad');
    
    window.clearInterval(autoInterval);
    if(router.currentView.locationData != undefined ){
        var locationData = '' || [];
        locationData = router.currentView.locationData;
//        for(var i = 0;i < locationData.length ;i++){
//            
//        }
        autoInterval = setInterval(function() {
            if(router.currentView.mapViewer != undefined ){
                console.log('DAO Template execute autoLoad map 3000ms.');
                router.currentView.locationData[i];
                var latitude = router.currentView.locationData[i].latitude;
                var longitude = router.currentView.locationData[i].longitude;
                console.log('i ' + i);
                console.log('latitude' + latitude);
                console.log('longitude' + longitude);
//                var param = '' || {};
                var mapEventClickMarkerhandle = function (evt){
                  OpenLayers.Event.stop(evt);
                };
              
                var paramMarkerPopup = {};
                paramMarkerPopup['deviceId'] = "gps_test";
                paramMarkerPopup['lon'] = longitude;
                paramMarkerPopup['lat'] = latitude;
//                paramMarkerPopup['popupContentHTML'] = Util.getPopupContentHTMLMapV2();
                paramMarkerPopup['imgUrl'] = IconUtil.getMapMarkerAlartIcon();
                paramMarkerPopup['mapEventClickMarkerhandle'] = mapEventClickMarkerhandle;
                paramMarkerPopup['closeBox'] = false;
                paramMarkerPopup['overflow'] = false;
                router.currentView.mapViewer.changeIconMarker(paramMarkerPopup);
                
                var param = '' || {};
                var toProjection = new OpenLayers.Projection("EPSG:900913");
                var lonlat = new OpenLayers.LonLat(longitude,latitude).transform(
                        new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
                        toProjection // to Spherical Mercator Projection
                );
                param['lon'] = longitude;
                param['lat'] = latitude;
//                param["lonlat"] = lonlat;
                param["radius"] = 0.5;
                router.currentView.mapViewer.drawCirlceAroundMarker(param);
                router.currentView.mapViewer.changeArrPointMarker(longitude,latitude);
                router.currentView.mapViewer.setMapCenterPoints();
                if(i == locationData.length-1){
//                    i = 0;
                    clearInterval(autoInterval);
                    alert("Game over!");
                }else{
                    i++;
                }
            }
//            OpenStreetMapUtil.updateInfoMarkersMap();
        }, 350);
    }
  
    
};
var container ;
var REQUIRE_UTILS_LIB = "require_utils";
var ROUTER_LIB = "router";
var TEXT_LIB = "text";
var DEPENDENCIES_LIB = [REQUIRE_UTILS_LIB,TEXT_LIB];
var router;
$(document).ready(function() {
    require(DEPENDENCIES_LIB, function() {
        require([ ROUTER_LIB ], function() {
            container = $("#container-content");
            router = new AppRouter();
            Backbone.history.start();
            initApp();
        });
//        var router = new Router();
//        Backbone.history.start();
        
    });
});